#include "precompiled.h"
#include "PianoEngine.h"

#include "AudioEngine/SineProducer.h"
#include "AudioEngine/VolumeEnvelope.h"

PianoEngine::PianoEngine(sp<Temperament> temperament)
	: envelope_parameters(0, 400, .5, 1000)
{
	this->temperament = temperament;
}

void PianoEngine::begin_playing_note(int note_id)
{
	using namespace AudioEngine;
	int freq = temperament->get_frequency(440.0, note_id + 3); // +3 because 440 is the note A and we want C
	sp<Producer> sine = new SineProducer(freq);
	sp<Producer const> envelope = new VolumeEnvelope(sine, envelope_parameters);
	sp<PlaySession> session = new PlaySession(envelope);
	play_sessions[note_id] = session;
}

void PianoEngine::begin_note_release(int note_id)
{
	AudioEngine::Producer* producer = const_cast<AudioEngine::Producer*>
		(play_sessions[note_id]->get_producer().get()); // hack... due to sp being crap
	producer->key_release();
	slot_container.connect(producer->sig_finished, this, &PianoEngine::on_session_finished, note_id);
}

void PianoEngine::on_session_finished(int note_id)
{
	play_sessions.erase(note_id);
}
